<template>
  <div class="app-main-content-box">
    <div class="index-dialog">
      <span class="text-dialog">首页弹窗</span>
      <el-button class="add-dialog" @click="toDialog">新增弹窗</el-button>
      <!-- 搜索 -->
      <div class="dialog-search">
        <el-form
          ref="filterForm"
          :inline="true"
          :rules="rules"
          size="small"
          :model="filterForm"
        >
          <el-form-item>
            <el-input
              v-model.trim="filterForm.title"
              placeholder="请输入标题"
              style="width: 250px"
              @keyup.enter.native="searchFn"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filterForm.popType"
              placeholder="请选择弹窗类型"
              filterable
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="filterForm.popState" placeholder="请选择状态">
              <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="validDate"
              :clearable="false"
              align="center"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              range-separator="~"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>

          <el-form-item>
            <template>
              <el-button type="primary" size="small" @click="searchFn"
                >搜索</el-button
              >
              <el-button size="small" @click="resetForm('filterForm')"
                >重置</el-button
              >
            </template>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <div class="list-table">
        <el-table
          size="medium"
          border
          :data="list"
          stripe
          style="width: 100%"
          empty-text="暂无数据"
          :span-method="arraySpanMethod"
        >
          <el-table-column prop="title" align="center" label="标题" />
          <el-table-column prop="popType" align="center" label="弹窗类型">
            <template v-slot="scope">
              <span v-if="scope.row.popType === 1">普通弹窗</span>
              <span v-if="scope.row.popType === 2">储值弹窗</span>
            </template>
          </el-table-column>
          <el-table-column
            class-name="dialog-table-box"
            prop="imgUrl"
            align="center"
            label="弹窗图"
          >
            <template v-slot="scope">
              <!-- <div class="row_box"> -->
              <!-- <div v-for="item in scope.row.ruleVos" :key="item.id"> -->
              <el-popover placement="right" title="" trigger="click">
                <img
                  slot="reference"
                  style="max-width: 50px"
                  :src="fileBaseUrl + scope.row.imgUrl"
                  alt=""
                />

                <img
                  :src="fileBaseUrl + scope.row.imgUrl"
                  alt=""
                  style="max-width: 800px"
                />
              </el-popover>
              <!-- </div> -->
              <!-- </div> -->
            </template>
          </el-table-column>
          <el-table-column
            class-name="dialog-table-box"
            prop="insideParams"
            align="center"
            label="站内链接"
          >
            <template v-slot="scope">
              <!-- <div class="row_box"> -->
              <!-- <div v-for="item in scope.row.ruleVos" :key="item.id"> -->
              <span>{{ JSON.parse(scope.row.insideParams).remark }}</span>
              <!-- </div> -->
            </template>
          </el-table-column>

          <el-table-column
            prop="showRule"
            align="center"
            label="显示设置"
            class-name="dialog-table-box"
          >
            <template v-slot="scope">
              <span v-if="scope.row.showRule === 0">每次进入程序显示</span>
              <span v-if="scope.row.showRule > 0"
                >{{ scope.row.showRule }}天显示一次</span
              >
              <span v-if="scope.row.showRule === -1"
                >规则星期每次进入店铺显示，每周指定星期:<span
                  v-if="scope.row.weeks"
                >
                  <span
                    style="padding-right: 5px"
                    v-for="(weeks, index) in scope.row.weeks.split(',')"
                    :key="index"
                    >{{ weeksFilter(weeks) }}</span
                  >
                </span>
              </span>
              <span v-if="scope.row.showRule === -2"
                >规则星期显示一次，每周指定星期：<span v-if="scope.row.weeks">
                  <span
                    style="padding-right: 5px"
                    v-for="(weeks, index) in scope.row.weeks.split(',')"
                    :key="index"
                    >{{ weeksFilter(weeks) }}</span
                  >
                </span></span
              >
            </template>
          </el-table-column>

          <el-table-column
            prop="readTimes"
            align="center"
            label="查阅量"
            class-name="dialog-table-box"
          >
          </el-table-column>
          <el-table-column
            prop="validDate"
            align="center"
            label="有效期"
            width="200"
          >
            <template slot-scope="scope">
              <span
                >{{
                  $dateFtt("yyyy-MM-dd hh:mm:ss", new Date(scope.row.startTime))
                }}
                ~
                {{
                  $dateFtt("yyyy-MM-dd hh:mm:ss", new Date(scope.row.endTime))
                }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="popState" align="center" label="状态">
            <template v-slot="scope">
              <span v-if="scope.row.popState === 1">未开始</span>
              <span v-if="scope.row.popState === 2">进行中</span>
              <span v-if="scope.row.popState === 3">已结束</span>
              <span v-if="scope.row.popState === 4">{{
                new Date(scope.row.endTime).getTime() <= new Date().getTime
                  ? "已结束"
                  : "已关闭"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                :disabled="
                  scope.row.popState === 3 ||
                  scope.row.popState === 4 ||
                  new Date(scope.row.endTime).getTime() <= new Date().getTime
                    ? true
                    : false
                "
                @click="editFn(scope.row)"
                >编辑</el-button
              >
              <el-button type="text" size="small" @click="checkFn(scope.row)"
                >查看</el-button
              >
              <el-button
                type="text"
                size="small"
                :disabled="scope.row.popState !== 1 ? true : false"
                @click="delFn(scope.row.id)"
                >删除</el-button
              >
              <el-button
                size="small"
                v-if="scope.row.popState === 2"
                type="text"
                @click="closeFn(scope.row.id)"
                >关闭</el-button
              >
              <el-button size="small" type="text" @click="copyFn(scope.row)"
                >复制</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total !== 0"
          :config="paginationConfig"
          :current-page.sync="paginationConfig.page"
          :page-sizes="paginationConfig.pageSizes"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  getMarketingPopConfigList,
  delPopById,
  closePop,
} from "@/api/marketing";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      loading: false,
      tableLoading: false,
      srcList: [],
      validDate: [],
      // 筛选
      filterForm: {
        title: "",
        popType: "",
        popState: "",

        startTime: "",
        endTime: "",
      },
      rules: {
        title: [
          { min: 1, max: 10, message: "长度在1到10之间", trigger: "blur" },
        ],
      },
      list: [],
      tableList: [],
      tempIndex: null,

      // 分页配置
      paginationConfig: {
        direction: "center", // 分页位置
        layout: "total, sizes, prev, pager, next, jumper", // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10, // 每页条数-默认10
      },
      // 配置筛选选项
      typeOptions: [
        {
          value: 1,
          label: "普通弹窗",
        },
        {
          value: 2,
          label: "储值弹窗",
        },
      ],
      stateOptions: [
        {
          value: 1,
          label: "未开始",
        },
        {
          value: 2,
          label: "进行中",
        },
        {
          value: 3,
          label: "已结束",
        },
        {
          value: 4,
          label: "已关闭",
        },
      ],
    };
  },
  watch: {
    searchSelect(val) {},
  },

  mounted() {
    this.curPage = Number(localStorage.getItem("curPage")) || 1;
    this.initData(this.curPage);
    localStorage.removeItem("curPage");
  },

  computed: {
    ...mapGetters(["fileBaseUrl", "curMenu"]),
    weeksFilter() {
      return function (week) {
        switch (week) {
          case "1":
            return "周日";
          case "2":
            return "周一";
          case "3":
            return "周二";
          case "4":
            return "周三";
          case "5":
            return "周四";
          case "6":
            return "周五";
          case "7":
            return "周六";
        }
      };
    },
  },
  methods: {
    toDialog() {
      this.$nextTick(() => {
        this.curMenu[this.curMenu.length - 1] = {
          ...this.curMenu[this.curMenu.length - 1],
          title: "新增弹窗",
        };
        this.$store.dispatch(
          "setCurmenu",
          JSON.parse(JSON.stringify(this.curMenu))
        );
      });
      this.$router.push({
        path: "/marketing/activity-dialog-edit",
        query: { pageType: "add", name: "MarketingActivityDialogAdd" },
      });
    },
    async initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.filterForm.pageNum = page;
      this.filterForm.pageSize = pageSize;
      const params = JSON.parse(
        JSON.stringify(Object.assign({}, this.filterForm))
      );
      // 清除多余字段
      for (const key in params) {
        if (params[key] === "" || params[key] === "all") {
          delete params[key];
        }
      }
      this.tableLoading = true;

      const res = await getMarketingPopConfigList(params);
      // let tableList = [];
      this.tableList = res.data.list;

      this.paginationConfig.total = res.data.total;
      this.paginationConfig.page = res.data.pageNum;

      // 处理this.list行数相同的数组记录每一行设置的合并数
      let tempMergeIndex = []; //接收合并的索引数组
      let pos = null; //索引
      let list = [];
      let keyObj = {};
      this.tableList.map((item) => {
        if (item.ruleVos && item.ruleVos.length > 0) {
          item.ruleVos.map((key) => {
            keyObj.imgUrl = key.imgUrl;
            keyObj.insideParams = key.insideParams;
            keyObj.readTimes = key.readTimes;
            keyObj.weeks = key.weeks;

            let dataObj = {
              ...item,
              ...keyObj,
            };
            // delete dataObj.ruleVos
            list.push(dataObj);
          });
        } else {
          list.push(item);
        }
      });
      for (let i = 0; i < list.length; i++) {
        if (i === 0) {
          tempMergeIndex.push(1);
          pos = 0;
        } else {
          if (list[i].id && list[i].id === list[i - 1].id) {
            tempMergeIndex[pos] += 1;
            tempMergeIndex.push(0);
          } else {
            tempMergeIndex.push(1);
            pos = i;
          }
        }
      }
      this.list = list;
      this.tempIndex = tempMergeIndex;
    },

    // 删除弹窗
    async delFn(id) {
      // 二次提醒
      await this.$confirm("是否确定删除当前弹窗内容", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
        roundButton: true,
      });
      this.loading = true;

      // 解决删除当前页最后一条信息时没显示数据
      const totalPage = Math.ceil(
        (this.paginationConfig.total - 1) / this.paginationConfig.pageSize
      );
      this.paginationConfig.page =
        this.paginationConfig.page > totalPage
          ? totalPage
          : this.paginationConfig.page;
      this.paginationConfig.page =
        this.paginationConfig.page < 1 ? 1 : this.paginationConfig.page;
      // 发请求
      await delPopById(id);
      // 提示
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000,
        offset: 40,
      });
      // 更新列表
      this.$forceUpdate();
      this.initData();
    },

    // 搜索
    searchFn() {
      this.filterForm.startTime = this.validDate[0];
      this.filterForm.endTime = this.validDate[1];
      this.loading = false;
      this.paginationConfig.page = 1;
      this.initData();
    },

    // 重置
    resetForm(formName) {
      (this.filterForm = {
        title: "",
        popType: "",
        popState: "",
        validDate: [],
      }),
        (this.validDate = "");
      this.$refs[formName].resetFields();
      this.initData(1);
    },

    // 分页sizes改变
    sizesChange() {
      this.initData();
    },

    // 分页page改变
    pageChange() {
      this.initData();
    },

    // 跳转
    checkFn({ id }) {
      this.$nextTick(() => {
        this.curMenu[this.curMenu.length - 1] = {
          ...this.curMenu[this.curMenu.length - 1],
          title: "查看弹窗",
        };
        this.$store.dispatch(
          "setCurmenu",
          JSON.parse(JSON.stringify(this.curMenu))
        );
      });
      localStorage.setItem("curPage", this.paginationConfig.page.toString());
      this.$router.push({
        path: "/marketing/activity-dialog-edit",
        query: { pageType: "check", id, name: "MarketingActivityDialogCheck" },
      });
    },
    editFn({ id, popState }) {
      localStorage.setItem("curPage", this.paginationConfig.page.toString());
      this.$router.push({
        path: "/marketing/activity-dialog-edit",
        query: {
          pageType: "edit",
          id,
          popState,
          name: "MarketingActivityDialogEdit",
        },
      });
    },
    // 复制弹窗,跳到新增页面
    copyFn({ id }) {
      this.$nextTick(() => {
        this.curMenu[this.curMenu.length - 1] = {
          ...this.curMenu[this.curMenu.length - 1],
          title: "新增弹窗",
        };
        this.$store.dispatch(
          "setCurmenu",
          JSON.parse(JSON.stringify(this.curMenu))
        );
      });
      localStorage.setItem("curPage", this.paginationConfig.page.toString());
      this.$router.push({
        path: "/marketing/activity-dialog-add",
        query: {
          pageType: "add",
          id,
          name: "MarketingActivityDialogAdd",
        },
      });
    },

    // 关闭弹窗
    async closeFn(id) {
      await this.$confirm("是否确定关闭当前弹窗内容？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
        roundButton: true,
      });
      await closePop(id);
      // 提示
      this.$notify({
        title: "成功",
        message: "关闭成功",
        type: "success",
        duration: 2000,
        offset: 40,
      });
      // 更新列表
      this.$forceUpdate();
      this.initData();
    },
    // 合并单元
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return {
          rowspan: this.tempIndex[rowIndex],
          colspan: 1,
        };
      }
      if (columnIndex === 1) {
        return {
          rowspan: this.tempIndex[rowIndex],
          colspan: 1,
        };
      }

      if (columnIndex === 6) {
        return {
          rowspan: this.tempIndex[rowIndex],
          colspan: 1,
        };
      }
      if (columnIndex === 7) {
        return {
          rowspan: this.tempIndex[rowIndex],
          colspan: 1,
        };
      }
      if (columnIndex === 8) {
        return {
          rowspan: this.tempIndex[rowIndex],
          colspan: 1,
        };
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.text-dialog {
  margin-right: 20px;
}
.dialog-search {
  margin-top: 18px;
  .el-form--inline {
    .el-form-item {
      margin-right: 20px;
    }
  }

  .el-button--small {
    display: inline-block;
    padding: 9px 25px;
  }
}

/deep/ .dialog-table-box {
  padding: 0;
  &.el-table__cell {
    padding: 0;
    .cell {
      top: 0;
      left: 0;
      // position: absolute;
      height: 100%;
      width: 100%;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      .row_box {
        height: 100%;
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        .row_item {
          padding: 5px 10px;
          width: 100%;
          flex: 1;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .row_item:not(:last-child) {
          border-bottom: 1px solid #ddd;
        }
      }
    }
  }
}
</style>

```
